<template>
  <div class="song-audio">
    <audio id="player"
           :src="url"
           controls = "controls"
           preload = "true"
           @canplay="startPlay"
           @ended="ended">
    </audio>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
export default {
  name: 'SongAudio',
  computed: {
    ...mapGetters([
      'id',
      'url',
      'isPlay'
    ])
  },
  watch: {
    // 监听播放还是暂停
    isPlay: function() {
      this.togglePlay()
    }
  },
  data() {
    return {
      // http://127.0.0.1:8888//song/1649666601081%E5%91%A8%E6%9D%B0%E4%BC%A6%20-%20%E5%BF%8D%E8%80%85.mp3?
      // url: 'http://127.0.0.1:8888//song/1649666601081%E5%91%A8%E6%9D%B0%E4%BC%A6%20-%20%E5%BF%8D%E8%80%85.mp3'
    }
  },
  methods: {
    startPlay() {
      let player = document.querySelector('#player')
      player.play()
    },
    // 播放完后触发
    ended() {
      this.isPlay = false
    },
    // 开始、暂停
    togglePlay() {
      let player = document.querySelector('#player')
      if (this.isPlay) {
        player.play()
      } else {
        player.pause()
      }
    }
  }
}
</script>

<style scoped>
  .song-audio {
    display: none;
  }
</style>
